<template>
  <el-row >   
    <el-col :push="20" :span="4">
    <code>
          当前时间:
         {{ currentTime }}
        </code>
      </el-col>
      </el-row>

    <div style="margin: 20px;">

      <el-row>
      <el-col  :span="2">
        <el-input  placeholder="请输入订单编号"  v-model="SelectRefundCommodityForm.commodityId"  style="width: 150px; margin-right: 10px;"  @change="selsectcommodityId" />
      </el-col>
      <el-col :push="2" :span="2">
        <el-input  placeholder="请输入收货地址"  v-model="SelectRefundCommodityForm.addressInfo"  style="width: 150px; margin-right: 10px;"  @change="selsectaddressInfo" />
      </el-col>

      <el-col :push="4" :span="2">
        <el-input  placeholder="请输入名字"  v-model="SelectRefundCommodityForm.receiverName"  style="width: 150px; margin-right: 10px;"  @change="selsectreceiverName" />
      </el-col>
      <el-col :push="6" :span="2">
        <el-input  placeholder="请输人收货人电话"  v-model="SelectRefundCommodityForm.receiverPhone"  style="width: 150px; margin-right: 10px;"  @change="selsecreceiverPhone" />
      </el-col>

      <el-col :push="8" :span="2">
  <el-select v-model="SelectRefundCommodityForm.paymentStatus" placeholder="请选择支付状态"  style="width: 150px" @change="selsectpaymentStatus">
    <el-option
      v-for="item in cities"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    /></el-select>
      </el-col>
    </el-row>



       

        <div v-for="(order,index) in RefundCommodityList" :key="index">
          <!-- 订单信息头部 -->
          <el-descriptions :title="`订单 ${index + 1} 信息`" :column="2" border>
            <el-descriptions-item label="订单编号">{{ order.commodityId}}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDate(order.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="收货人">{{ order.receiverName }} ({{ order.receiverPhone }})</el-descriptions-item>
            <el-descriptions-item label="地址">{{ order.addressInfo }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">
              {{ paymentStatusText(order.paymentStatus) }}
            </el-descriptions-item>
            <el-descriptions-item label="发货状态">{{shippingStatusText(order.shippingStatus) }}

              <el-popover
    placement="bottom"
    title="物流单号"
    :width="200"
    trigger="click"
  >
                <!-- 使用插槽动态设置 Popover 内容 -->
  <div >
    <p>{{ order.oddNumbers==0? '暂无单号': order.oddNumbers}}</p>

    <el-button type="text" size="small" >查看物流信息</el-button>
  </div>


    <template #reference>
      <el-button class="m-2"  type="text" style="margin-left: 20px;">查看物流单号</el-button>
    </template>
  </el-popover>


            </el-descriptions-item>
            <el-descriptions-item label="退款状态" v-if="order.refund!=0">{{ refundText(order.refund) }}
  <el-popover
    placement="bottom"
    title="退款原因"
    :width="200"
    trigger="click"
  >
                <!-- 使用插槽动态设置 Popover 内容 -->
  <div v-if="RefundRequests">
    <p>{{ RefundRequests.reason || '暂无退款原因' }}</p>
  </div>


    <template #reference>
      <el-button class="m-2" @click="selsectyuanyin(order)" type="text" style="margin-left: 20px;">退款原因</el-button>
    </template>
  </el-popover>



</el-descriptions-item>

          </el-descriptions>
          
  
          <!-- 商品列表表格 -->
          <el-table :data="order.commodityDetails || []" style="width: 100%; margin-top: 20px;" stripe>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="price" label="单价" width="180">
              <template #default="scope">￥{{ scope.row.price }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="180"></el-table-column>
            <el-table-column label="总价" width="180">
              <template #default="scope">￥{{ scope.row.totalPrice }}</template>
            </el-table-column>
            <el-table-column prop="notes" label="备注"></el-table-column>
          </el-table>
  
          <!-- 订单总金额 -->
          <div class="order-total" style="text-align: right; margin-top: 20px;">
          <el-row>
            <el-col :span="4">
              <span >订单总金额：￥{{ order.total }}</span>
            </el-col>

            <el-col :push="14" :span="4">
              <span>折扣后价格：￥{{ order.discountedPrices }}</span>
            </el-col>
          </el-row>
            
            <el-button  v-if="order.refund === 1 && order.paymentStatus==1 && order.paymentMethod==3"  style="margin-left: 20px;"  type="text">微信退款</el-button>
            <el-button  v-if="order.refund === 1 && order.paymentStatus==1 && order.paymentMethod==2"  style="margin-left: 20px;"  type="text"  @click="BalanceRefund(order)">余额退款</el-button>
            <el-button  v-if="order.refund === 1 && order.paymentStatus==1  && order.paymentMethod==1 " style="margin-left: 20px;"  type="text" @click="AlipayRefund(order)">支付宝退款</el-button>
            <el-button type="text" v-if="order.refund === 1 && order.paymentStatus==1" @click="RefuseRefund(order)" style="margin-left: 20px;">拒绝退款</el-button>
          </div>
          <hr />
        </div>




        <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="SelectRefundCommodityForm.pageNum"
      v-model:page-size="SelectRefundCommodityForm.pageSize"
      :page-sizes="[1, 4, 6, 8]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="RefundCommodityTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>


  <el-dialog
    v-model="isShow22"
    title="请输入驳回原因"
    width="500"
    :before-close="handleClose"
  >
    <span>
     <input type="text" v-model="RefuseRefundForm.indentId" placeholder="请输入驳回原因">
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow22 = false">取消</el-button>
        <el-button type="primary" @click="Confirm">确认</el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog
    v-model="Show11"
    title="确认退款？"
    width="500"
    :before-close="handleClose"
  >
    <span>确认进行退款？ 此操作将无法撤回</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="Show11 = false">取消</el-button>
        <el-button type="primary" @click="sure">确认</el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog
    v-model="isShow333"
    title="确认退款？"
    width="500"
    :before-close="handleClose"
  >
    <span>确认进行退款？ 此操作将无法撤回</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow333 = false">取消</el-button>
        <el-button type="primary" @click="sureAlipayRefund">确认</el-button>
      </div>
    </template>
  </el-dialog>

     

  
  <div v-if="payUrl">
          <p>退款链接已生成：</p >
          <a :href="payUrl" target="_blank">{{ payUrl }}</a >
      </div>


    </div>
  </template>
  
  <script>
  export default {
    name: 'ManagerRefundCommodity',
    data() {
      return {
        RefundCommodityList:[],
        RefundCommodityTotal:0,
        SelectRefundCommodityForm:{
pageNum: 1,
    pageSize: 10,
    commodityId: null,
    commodityName: null,
    addressInfo: null,
    receiverName: null,
    receiverPhone: null,
    paymentStatus: null,
    shippingStatus: null,
    createdAt: null
        },
        commodityId:0,
        RefundRequests:null,
        currentTime: '',
        intervalId: null, // 用于存储定时器ID
        order:null,
        isShow22: false,
        RefuseRefundForm:{
          commodityId:null,
          indentId:null,
        },
        PayForm:{
          amount:0,
          commodityId:""
        },
        Show11: false,
        Show12: false,


        RefundForm:{
            amount:0,
            commodityId:""
          },
          payUrl: "", // 生成的退款链接
          isShow333:false,
      };
    },
    methods: {

      sureAlipayRefund(){
            this.$http.post('/order/commodity/refund',this.RefundForm).then(resp=>{
           // 将响应数据中的"data"属性值写入到文档中
              document.write(resp.data.data)
            }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
      },

      AlipayRefund(order){
        this.RefundForm.amount=order.discountedPrices
        this.RefundForm.commodityId=order.commodityId
        this.isShow333 = true
      },

      sure(){
        this.$http.post("/order/commodity/balancerefund",this.PayForm)
        .then(resp => {
          if(resp.data.code==200){
            this.$message.success("已退款");
            this.selsectRefundCommodity();
            this.Show11 = false
          }else{
            this.$message.error("操作失败");
          }
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
      },
      BalanceRefund(order){
        this.PayForm.amount=order.discountedPrices
        this.PayForm.commodityId=order.commodityId
        this.Show11 = true

      },
      Confirm(){
        this.$http.post("/order/refundRequests/RefuseRefund",this.RefuseRefundForm)
        .then(resp => {
          if(resp.data.code==200){
            this.$message.success("已拒绝退款");
            this.selsectRefundCommodity();
          }else{
            this.$message.error("操作失败");
          }
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
      },
      RefuseRefund(obj){
        this.RefuseRefundForm.commodityId=obj.commodityId
        this.isShow22 = true;

      },
      RefundMoney(obj){
        this.order=obj
        

      },
      selsectcommodityId() {
      if (this.SelectRefundCommodityForm.commodityId == null) {
        alert("请输入订单编号");
        return;
      }
      this.selsectRefundCommodity();
    },
        selsectpaymentStatus(){
      console.log(this.SelectRefundCommodityForm.paymentStatus);
      this.selsectRefundCommodity();

    },
    selsecreceiverPhone(){
      if (this.SelectRefundCommodityForm.receiverPhone == null) {
        alert("请输入收货人电话");
        return;
      }
      this.selsectRefundCommodity();
    },
    selsectreceiverName(){
      if (this.SelectRefundCommodityForm.receiverName == null) {
        alert("请输入收货人名字");
        return;
      }
      this.selsectRefundCommodity()
    },

    selsectaddressInfo(){
      if (this.SelectRefundCommodityForm.addressInfo == null) {
        alert("请输入订单地址");
        return;
      }
      this.selsectRefundCommodity()

    },
      updateTime() {
            const now = new Date();
            this.currentTime = this.formatDate(now);
          },
      selsectyuanyin(obj){
        console.log(obj);
        this.$http.get("/order/refundRequests/selectrefund",{
      params:{

            commodityId:obj.commodityId
      }
          }).then(resp=>{
        
          this.RefundRequests=resp.data.data;
          console.log(this.RefundRequests);
      
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });

      },
  //         selsectRefundCommodity() {
  //   this.$http.post('/order/commodity/selsectrefundcommoditymanager',this.SelectRefundCommodityForm)
  //     .then(resp => {
  //   this.RefundCommodityList = resp.data.data.list;
  //   this.RefundCommodityTotal = resp.data.data.total;

  //   if(this.RefundCommodityTotal == 0){
  //     this.$message.error('没有退款订单');
  //   }
  //     });
  // },


  // 选择退款商品的方法
  selsectRefundCommodity() {
    this.$http.post('/order/commodity/selsectrefundcommoditymanager',this.SelectRefundCommodityForm)
      .then(resp => {
        // 获取退款商品列表
        this.RefundCommodityList = resp.data.data.list;

        // 对订单进行排序，申请退款的在前，已处理退款的在后
        this.RefundCommodityList.sort((a, b) => {
          console.log('Sorting:', a.refund, b.refund); // 调试输出
          return Number(a.refund) - Number(b.refund); // 确保是数字比较
        });

        // 获取退款商品总数
        this.RefundCommodityTotal = resp.data.data.total;
        
        if (this.RefundCommodityTotal === 0) {
          this.$message.error('没有退款订单'); // 显示“没有退款订单”
        }
      }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
  },






        handleSizeChange(val){
            this.SelectRefundCommodityForm.pageSize = val
            this.selsectRefundCommodity()    
        },
        handleCurrentChange(val){
            this.SelectRefundCommodityForm.pageNum = val
            this.selsectRefundCommodity()    
        },
      formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      },
      refundText(status){
    const statusMap = {
      0: '未申请退款',
      1: '待处理',
      2: '已同意',
      3: '已拒绝',
    };
    return statusMap[status] || '未知状态';
  },
      paymentStatusText(status) {
        return status === 1 ? '已支付' : '未支付';
      },
      shippingStatusText(status) {
        const statusMap = ['未发货', '已发货', '已签收', '退货中', '已退货'];
        return statusMap[status] || '未知状态';
      },
      startPolling() {

this.intervalId = setInterval(() => {
this.updateTime()

}, 5000); // 每5秒轮询

},

stopPolling() {

clearInterval(this.intervalId); // 清理定时器

},
    },
    mounted() {
      this.selsectRefundCommodity()
      this.updateTime()
      this.startPolling(); // 开始轮询

    },

beforeUnmount() {

 this.stopPolling(); // 组件卸载前清理定时器

}
  };
  </script>
  
  <style scoped>
  /* 样式可以根据需要调整 */
  .custom-box-card {
  width: 300px;
  height: 100px;
}

.card-header {
  text-align: center;
  font-size: 1.2em;
  background-color: #f0f0f0;
}

.card-content {
  text-align: center;
  line-height: 60px;
  font-weight: bold;
}
  </style>